#include "my_wifi.h"
#include "mqtt_chat.h"
// #include "../../main/show.h"

/* FreeRTOS event group to signal when we are connected & ready to make a request */
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event,
   but we only care about one event - are we connected
   to the AP with an IP? */
static const int CONNECTED_BIT = BIT0;
static const int ESPTOUCH_DONE_BIT = BIT1;
static const char *TAG = "smartconfig_example";

static void smartconfig_example_task(void * parm);

char SSID[33];
char IP[20];

int8_t NET_RSSI = -100;

uint8_t wifi_power = 1,wifi_state = 0,wifi_state_change = 0;
uint8_t timeout = 0;

static void event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {//开始连接事件
        xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 4*1024, NULL, 3, NULL); 
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {//连接失败事件
        if(wifi_power){//开关开启状态下
            wifi_state = 0;
            wifi_state_change = 1;
            if(timeout == 0){
                timeout = 1;
                esp_wifi_disconnect();
                ESP_LOGI(TAG, "start to config");
                ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS) );//支持APP ESPTOUCH和微信AIRKISS
                smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
                ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );
            }
            if(timeout == 2){
                esp_wifi_connect();//尝试重连
                xEventGroupClearBits(s_wifi_event_group, CONNECTED_BIT);  
            }
        }
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { //如果是ip获取事件，获取到了ip就打印出来
        xEventGroupSetBits(s_wifi_event_group, CONNECTED_BIT);
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG, "static ip:" IPSTR, IP2STR(&event->ip_info.ip));
        wifi_state = 1;
        wifi_state_change = 1;
        snprintf(IP, sizeof(IP), IPSTR, IP2STR(&event->ip_info.ip));
        printf("GET:%s\r\n",IP);
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_SCAN_DONE) {
        ESP_LOGI(TAG, "Scan done");
        wifi_state = 2;
        wifi_state_change = 1;
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_FOUND_CHANNEL) {
        ESP_LOGI(TAG, "Found channel");
        wifi_state = 3;
        wifi_state_change = 1;
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD) {
        timeout = 2;
        ESP_LOGI(TAG, "Got SSID and password");
        wifi_state = 4;
        wifi_state_change = 1;

        smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data;
        wifi_config_t wifi_config;
        uint8_t ssid[33] = { 0 };
        uint8_t password[65] = { 0 };
        uint8_t rvd_data[33] = { 0 };

        bzero(&wifi_config, sizeof(wifi_config_t));
        memcpy(wifi_config.sta.ssid, evt->ssid, sizeof(wifi_config.sta.ssid));
        memcpy(wifi_config.sta.password, evt->password, sizeof(wifi_config.sta.password));
        wifi_config.sta.bssid_set = evt->bssid_set;
        if (wifi_config.sta.bssid_set == true) {
            memcpy(wifi_config.sta.bssid, evt->bssid, sizeof(wifi_config.sta.bssid));
        }

        memcpy(ssid, evt->ssid, sizeof(evt->ssid));
        memcpy(password, evt->password, sizeof(evt->password));
        ESP_LOGI(TAG, "SSID:%s", ssid);
        ESP_LOGI(TAG, "PASSWORD:%s", password);
        snprintf(SSID, sizeof(SSID), "%s", ssid);
        printf("GET:%s\r\n",SSID);
        if (evt->type == SC_TYPE_ESPTOUCH_V2) {
            ESP_ERROR_CHECK( esp_smartconfig_get_rvd_data(rvd_data, sizeof(rvd_data)) );
            ESP_LOGI(TAG, "RVD_DATA:");
            for (int i=0; i<33; i++) {
                printf("%02x ", rvd_data[i]);
            }
            printf("\n");
        }

        ESP_ERROR_CHECK( esp_wifi_disconnect() );
        ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
        esp_wifi_connect();
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE) {
        xEventGroupSetBits(s_wifi_event_group, ESPTOUCH_DONE_BIT);
    }
}

void initialise_wifi(void)
{
    ESP_ERROR_CHECK(esp_netif_init());
    s_wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    ESP_ERROR_CHECK(esp_netif_set_hostname(sta_netif, "LSH_ESP32"));// 不建议使用汉字

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );

    ESP_ERROR_CHECK( esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL) );
    ESP_ERROR_CHECK( esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL) );
    ESP_ERROR_CHECK( esp_event_handler_register(SC_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL) );

    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK( esp_wifi_start() );
}

static void smartconfig_example_task(void * parm)
{
    EventBits_t uxBits;


    wifi_config_t myconfig = {0};
 
    ESP_LOGI(TAG, "creat smartconfig_example_task");
    
    // 获取wifi配置信息，如果配置过，就直接连接wifi
    esp_wifi_get_config(ESP_IF_WIFI_STA, &myconfig);
    if (strlen((char*)myconfig.sta.ssid) > 0)
    {
        ESP_LOGI(TAG, "alrealy set, SSID is :%s,start connect", myconfig.sta.ssid);
        snprintf(SSID, sizeof(SSID), "%s", myconfig.sta.ssid);
        printf("GET:%s\r\n",SSID);
        esp_wifi_connect();
    }
    // 如果没有配置过，就进行配网操作
    else
    {
        ESP_LOGI(TAG, "have no set, start to config");
        ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS) );//支持APP ESPTOUCH和微信AIRKISS
        smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
        ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );
    }

    // ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS) );
    // smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    // ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );

    
    while (1) {
        uxBits = xEventGroupWaitBits(s_wifi_event_group, CONNECTED_BIT | ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY);
        if(uxBits & CONNECTED_BIT) {
            ESP_LOGI(TAG, "WiFi Connected to ap");
            mqtt_init();
            vTaskDelete(NULL);
        }
        if(uxBits & ESPTOUCH_DONE_BIT) {
            ESP_LOGI(TAG, "smartconfig over");
            esp_smartconfig_stop();
            vTaskDelete(NULL);
        }
    }
}


int8_t wifi_information_scanning(void){
    uint16_t number = 1;
    uint16_t ap_count = 0;

    wifi_ap_record_t ap_info[1];
    wifi_config_t wifi_sta_cfg;

    ESP_LOGI(TAG,"start scan");
    memset(ap_info, 0, sizeof(ap_info));
    if (esp_wifi_get_config(WIFI_IF_STA, &wifi_sta_cfg) != ESP_OK)//获取已连接的ap参数
    {
        ESP_LOGI(TAG, "esp_wifi_get_config err");  
        return -90;
    }

    wifi_scan_config_t scan_config = { 0 };
    scan_config.ssid = wifi_sta_cfg.sta.ssid;//限制扫描的ap的ssid
    scan_config.bssid = wifi_sta_cfg.sta.bssid;//限制扫描的ap的mac地址
    esp_wifi_scan_start(&scan_config, true);//阻塞扫描ap，scan_config为扫描的参数
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));//获取扫描到的ap信息
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));
    //获取扫描到的ap数量，因为限制了ssid和mac，因此最多只会扫描到1个
    for (int i = 0; (i < 1) && (i < ap_count); i++) {
        ESP_LOGI(TAG, "SSID \t\t%s", ap_info[i].ssid);
        ESP_LOGI(TAG, "RSSI \t\t%d", ap_info[i].rssi);
        ESP_LOGI(TAG, "Channel \t\t%d", ap_info[i].primary);
        ESP_LOGI(TAG, "BSSID: \t\t%02x:%02x:%02x:%02x:%02x:%02x", 
                                                        ap_info[i].bssid[0],
                                                        ap_info[i].bssid[1],
                                                        ap_info[i].bssid[2],
                                                        ap_info[i].bssid[3],
                                                        ap_info[i].bssid[4],
                                                        ap_info[i].bssid[5]);
    }
    esp_wifi_scan_stop(); 
    //from start to stop need 3210ms
    ESP_LOGI(TAG,"stop scan\r\n");

    NET_RSSI=ap_info[0].rssi;

    return ap_info[0].rssi;
}
